package net

import (
	"fmt"
	"github.com/gorilla/websocket"
	"net/http"
)

type Server struct {
	addr       string
	router     *Router
	needSecret bool
}

// Router Server添加路由
func (s *Server) Router(router *Router) {
	s.router = router
}
func (s *Server) NeedSecret(needSecret bool) {
	s.needSecret = needSecret
}

// NewServer 实例化server
func NewServer(addr string) *Server {
	return &Server{
		addr: addr,
	}

}
func (s *Server) Start() {
	http.HandleFunc("/", s.wsHandle)
	err := http.ListenAndServe(s.addr, nil)
	if err != nil {
		panic("服务启动失败:" + err.Error())
	}

}

var upgrader = websocket.Upgrader{
	// 解决跨域问题
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func (s *Server) wsHandle(w http.ResponseWriter, r *http.Request) {
	wsConn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		fmt.Println("websocket连接服务失败：" + err.Error())
	}
	fmt.Println("websocket连接服务成功！")
	//发消息的时候 把 消息当路由去处理 消息是有格式的 先定义消息的格式
	//err = wsConn.WriteMessage(websocket.BinaryMessage, []byte("hello"))
	//if err != nil {
	//	fmt.Println(err)
	//}
	//WsServer := NewWsServer(wsConn, s.needSecret)
	WsServer := Mgr.NewConn(wsConn, s.needSecret)
	//WsServer添加路由
	WsServer.Router(s.router)
	//执行
	WsServer.Start()
	//握手
	WsServer.Handshake()
}
